<?php

class Painel_FornecedorController extends App_Controller_Action
{

    private $_table     = 'FORNECEDOR';
    private $_pk        = 'FOR_ID';
    private $_order_col = 'FOR_NOM';
    private $_order     = 'ASC';
    private $_sta_col   = 'FOR_STA';
    private $obj        = '';
    private $form       = '';
    private $_file_col  = 'FOR_FILE'; 
    public  $dir = 'public/upload/clientes/';
    public  $db = '';
    
    public function init()
    {
        if($this->getRequest()->getActionName() == 'edit') $this->form = new Painel_Form_Fornecedor();        
    }

    public function indexAction() {
        
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('dominio','library');
        
        $where = 'WHERE '.$this->_pk . ' > 0';
        
        $dscfiltro = $this->_getParam('dscfiltro', '');
        if($dscfiltro > '') $where .= ' and FOR_NOM like "%'. $dscfiltro.'%" ';
        $this->view->dscfiltro = $dscfiltro;
        
        $query = 'SELECT SQL_CACHE B.*,E.EST_UF,C.CID_NOM FROM '.$this->_table.' B, ESTADOS E , CIDADES C '.$where.' AND B.EST_ID = E.EST_ID AND B.CID_ID = C.CID_ID ORDER BY '.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result);
        
    }
    
    public function editAction() {
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_pdr.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_fornecedor.js?1='.rand(1,3423));
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskMoney.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/mask.js');
        
        Zend_Loader::loadClass('imagem','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('dominio','library');
        
        //$this->view->view = 'view';
        
        $this->view->form = $this->form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                if($this->form->isValid($formData)) {
                    
                    $id = (int) $this->form->getValue($this->_pk);
                    
                    //$returnImg = imagem::upload($this->_file_col,$this->dir,$id);
                    
                    $data = $this->form->getValues();
                    
                    unset($data['img']);
                    unset($data[$this->_file_col]);
                    unset($data['br']);
                    
                    $this->db->beginTransaction();
                    if($id == 0){
                        $this->db->insert($this->_table, $data);
                        $id =  $this->db->lastInsertId();   
                        //imagem::rename($id,$this->dir,$returnImg['filenew']);
                    }
                    else $this->db->update($this->_table, $data,$this->_pk.' = ' . $id);
                    
                    //foreach(glob($this->dir.$id.'.*') as $img) imagem::reize($img,$img,'390','150');
                    
                    $this->db->commit();
                    
                    $this->_helper->redirector('index');           
                } else {
                    $this->form->populate($formData);
                }
            } catch(Exception $ex) {
                //Zend_Loader::loadClass('errordb','library');
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                $this->form->populate($formData);
                $this->db->rollBack();
            }
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $data = $this->db->fetchRow('SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$this->_pk . ' = ' . $id);
                $this->form->populate($data);
            }
        }
    }

    public function deleteAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $msg = '';
        $id = $this->_getParam('id', 0);
        if((int) $id > 0 ) {   
            $this->db->beginTransaction();
            try {
                $ok = (bool) $this->db->delete($this->_table, $this->_pk . ' = ' . $id);
                $this->db->commit();
            } catch(Exception $ex) {
                //echo getMessage();
                $ok = FALSE;
                $msg = MSG_DELETE;
                $this->db->rollBack();
            }             
        }       
        echo json_encode(array('ok' => $ok, 'msg'=> $msg));
        //$this->_helper->redirector('index');
    }
    
    public function buscacidadesAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $html = '';
        $select = '';
        $for_id = $this->_getParam('for_id', 0);
        $est_id = $this->_getParam('est_id', 0);
        
        if($for_id > 0){
            $data = $this->db->fetchRow('SELECT SQL_CACHE EST_ID,CID_ID FROM '.$this->_table.' WHERE '.$this->_pk . ' = ' . $for_id);
        }
        
        $ok = TRUE;
        $query = 'SELECT SQL_CACHE * FROM CIDADES WHERE EST_ID = '.$est_id.' AND CID_STA = 1 ORDER BY CID_NOM ASC';
        $result = $this->db->fetchAll($query);
        $arr = array();
        foreach($result as $r){
            $select = $r['EST_ID'] == $data['EST_ID'] && $r['CID_ID'] == $data['CID_ID']  ? 'selected':'';
            $html .= '<option '.$select.' value="'.$r['CID_ID'].'">'.$r['CID_NOM'].'</option>';
        }
        
        echo json_encode(array('ok' => $ok,'html'=>$html));
    }
    
}